package com.itech.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

public class UtilHttp {
	public static final int CONN_TIME_OUT = (1000 * 5);//5 sec or 5000 ms;
	private int connTimeOut = CONN_TIME_OUT;
	
	public UtilHttp() {
		
	}
	
	public UtilHttp(int connTimeOut) {
		this.connTimeOut = connTimeOut * 1000;
	}

	public void downloadHttpResponseToFile(String urlString, String fileName) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			URL url = new URL(urlString );
			URLConnection urlCon = url.openConnection();
			urlCon.connect();
			
			bis = new BufferedInputStream(urlCon.getInputStream());

			File file = new File(fileName);
			bos = new BufferedOutputStream(
					new FileOutputStream(file));

			byte[] data = new byte[1024];
			int downloadedLength = 0;
			int readCount = bis.read(data);
			while (readCount > 0) {
				bos.write(data, 0, readCount);
				downloadedLength = downloadedLength + readCount;
				readCount = bis.read(data);
			}
			bos.flush();
		} catch (Exception ex) {
			ex.printStackTrace(); // NOPMD
		} finally {
			if ((bis != null)) {
				try {
					bis.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				} finally {
					bis = null;
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				} finally {
					bos = null;
				}
			}
		}
	}
	
	public String getHttpResponse(String urlString) {
		StringBuffer sb = new StringBuffer(10000);
		try {
			URL url = new URL(urlString );
			URLConnection urlCon = url.openConnection();
			urlCon.setConnectTimeout(connTimeOut);
			urlCon.connect();
			InputStream in = new BufferedInputStream(urlCon.getInputStream());
			Reader reader = new InputStreamReader(in , "UTF-8");
		    int c;
		    while ((c = in.read()) != -1) sb.append((char) c);
		    reader.close();
		    in.close();
		} catch (Exception ex) {
			return null;
		} finally {
			
		}
		byte a = 3, b = 5;
		byte c = ++a;
		return sb.toString();
	}
}
